<template>
  <div class="auth-page">
    <div class="container page">
      <div class="row">
        <div class="col-md-6 offset-md-3 col-xs-12">
          <h1 class="text-xs-center">{{ isLogin ? "Sign in" : "Sign up" }}</h1>
          <p class="text-xs-center">
            <nuxt-link v-if="isLogin" to="/register"
              >Need an account?</nuxt-link
            >
            <nuxt-link v-else to="/login">Have an account?</nuxt-link>
          </p>

          <ul class="error-messages">
            <li v-for="(value, key) in errors" :key="key">
              {{ key }}:{{ value }}
            </li>
          </ul>

          <form @submit.prevent="onSubmit">
            <fieldset class="form-group" v-if="!isLogin">
              <input
                class="form-control form-control-lg"
                type="text"
                placeholder="Your Name"
                v-model="username"
                required
              />
            </fieldset>
            <fieldset class="form-group">
              <input
                class="form-control form-control-lg"
                type="email"
                placeholder="Email"
                v-model="user.email"
                required
              />
            </fieldset>
            <fieldset class="form-group">
              <input
                class="form-control form-control-lg"
                type="password"
                placeholder="Password"
                v-model="user.password"
                required
              />
            </fieldset>
            <button class="btn btn-lg btn-primary pull-xs-right">
              {{ isLogin ? "Sign in" : "Sign up" }}
            </button>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { login, register } from "../../http/user";
// 这样引入的目的是只在客户端的时候引入 js-cookie
const Cookie = process.client?require('js-cookie'):undefined
export default {
  middleware:'authenticatedlogin',
  name: "LoginPage",
  computed: {
    isLogin() {
      return this.$route.name === "login";
    },
  },
  data() {
    return {
      user: {
        username: "",
        email: "",
        password: "",
      },
      errors: {},
    };
  },
  methods: {
    async onSubmit() {
      try {
        // 判断是否是登录页面
        const result = this.isLogin
          ? await login({ user: this.user })
          : await register({ user: this.user });
        if (result.status === 200) {
          this.$router.push("/");
          this.$store.commit("setUser", result.data.user);

          // 为了防止浏览器刷新的时候数据丢失，我们要做数据持久化
          Cookie.set('user', result.data.user)
        }
      } catch (err) {
        this.errors = err.response.data.errors;
      }
    },
  },
  created() {
  },
};
</script>

<style>
</style>